
<template>
  <div class="app-container"  v-loading="loading">
	  <div class="search-container  app_ny">
	  	<div class="div2" style="position: relative">
	  		<el-row :gutter="12" style="width: 100%">
	  			<el-col :span="3">
	  				<el-input
	  				  v-model="queryParams.name"
	  				  placeholder="请输入菜单名称"
	  				  clearable
	  				  @keyup.enter="handleQuery"/>
	  			</el-col>
	  		
	  			<el-col :span="6" >
	  				<el-button  :loading="loading"  type="primary" @click="handleQuery"><template
	  					#icon><i-ep-search /></template>查询</el-button>
	  			</el-col>
	  		</el-row>
	  		<FilterColumn
	  		 class="filtBox"
	  		 @handleRefresh="resetQuery()"
	  		 :columns="false"></FilterColumn>
	  	</div>	
	  </div>
    <el-card shadow="never" size="small">
	  <div class="action-row">
	  	<el-button
	  	  v-hasPerm="['Menus/save']"
	  	  type="primary"
	  	  @click="openDialog(0)" plain>
	  	  <template #icon><i-ep-plus /></template> 新增</el-button>
	  </div>
      <el-table
        v-loading="loading"
        :data="menuList"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        row-key="id"
        default-expand-all
        border
        size="small"
        @row-click="onRowClick"
      >
	  <el-table-column type="index" label="序号" align="center" width="80" />
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <svg-icon
              :icon-class="
                scope.row.type === MenuTypeEnum.BUTTON || scope.row.type === MenuTypeEnum.DATA
                  ? 'button'
                  : scope.row.icon
              "
            />
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type == MenuTypeEnum.CATALOG">目录</el-tag>
            <el-tag v-if="scope.row.type == MenuTypeEnum.MENU" type="success"
              >菜单</el-tag
            >
            <el-tag v-if="scope.row.type == MenuTypeEnum.BUTTON" type="danger"
              >按钮</el-tag
            >
						<el-tag v-if="scope.row.type == MenuTypeEnum.DATA" type="warning"
              >数据权限</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          label="请求路由"
          align="left"
          width="150"
          prop="route"
        />

        <el-table-column
          label="请求方式"
          align="left"
          width="70"
          prop="method"
        />
        
        <el-table-column
          label="组件路由"
          align="left"
          width="100"
          prop="menu_path"
        />

        <el-table-column
          label="组件路径"
          align="left"
          width="250"
          prop="path"
        />

        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
						<el-switch
								
								v-model="scope.row.status"
								active-text="正常"
								inactive-text="禁用"
								:active-value="1"
								:inactive-value="0"
								inline-prompt
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
								@change="onStatusChange(scope.row)"
						/>
          </template>
        </el-table-column>

        <el-table-column label="菜单是否可见" align="center" min-width="100">
          <template #default="scope">
						<el-switch
								v-model="scope.row.is_show"
								active-text="显示"
								inactive-text="隐藏"
								inline-prompt
								:active-value="1"
								:inactive-value="0"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #a1a0a0"
								@change="onShowChange(scope.row)"
						/>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="80" prop="sort" />

        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.type !== MenuTypeEnum.DATA"
              v-hasPerm="['Menus/save']"
              type="success"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
            ><template #icon><i-ep-plus /></template>新增
            </el-button>

            <el-button
              v-hasPerm="['Menus/update']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(undefined, scope.row.id)"
            ><template #icon><i-ep-edit /></template>编辑
            </el-button>
            <el-button
              v-hasPerm="['Menus/delete']"
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><template #icon><i-ep-delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      destroy-on-close
      append-to-body
      width="750px"
      @close="closeDialog"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="父级菜单" prop="pid">
          <el-tree-select
            v-model="formData.pid"
            placeholder="选择上级菜单"
            :data="menuOptions"
            :props="menuProps"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="onMenuTypeChange">
            <el-radio label="CATALOG">目录</el-radio>
            <el-radio label="MENU">菜单</el-radio>
            <el-radio label="BUTTON">按钮</el-radio>
            <el-radio label="DATA">数据权限</el-radio>
          </el-radio-group>
        </el-form-item>

      
        <el-form-item v-if="formData.type !== MenuTypeEnum.CATALOG" label="请求路由"  prop="route">
          <el-input v-model="formData.route" placeholder="user" />
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuTypeEnum.CATALOG" label="请求方式" prop="method">
          <el-radio-group v-model="formData.method">
            <el-radio label="get">GET</el-radio>
            <el-radio label="post">POST</el-radio>
            <el-radio label="put">PUT</el-radio>
            <el-radio label="delete">DELETE</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON && formData.type !== MenuTypeEnum.DATA" label="页面路由"  prop="menu_path">
          <el-input v-model="formData.menu_path" placeholder="user" />
        </el-form-item>

        <!-- 组件页面完整路径 -->
        <el-form-item
          v-if="formData.type == MenuTypeEnum.MENU"
          label="页面路径"
          prop="path"
        >
          <el-input
            v-model="formData.path"
            placeholder="system/user/index"
            style="width: 95%"
          >
            <template v-if="formData.type == MenuTypeEnum.MENU" #prepend
              >src/views/</template
            >
            <template v-if="formData.type == MenuTypeEnum.MENU" #append
              >.vue</template
            >
          </el-input>
        </el-form-item>

        <el-form-item
          v-if="formData.type !== MenuTypeEnum.BUTTON && formData.type !== MenuTypeEnum.DATA"
          label="图标"
          prop="icon"
        >
          <!-- 图标选择器 -->
          <icon-select v-model="formData.icon" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON && formData.type !== MenuTypeEnum.DATA" label="隐藏菜单">
          <el-radio-group v-model="formData.is_show">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
import {Switch} from "@element-plus/icons-vue";

defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Menu",
  inheritAttrs: false,
});

import { MenuQuery, MenuForm, MenuVO } from "@/api/menu/types";
import {
  getMenuForm,
  listMenuOptions,
  addMenu,
  deleteMenu,
  updateMenu,
	setStatusMenu,
	setShowMenu,
} from "@/api/menu";

const api = inject('$base', null as any);

import { MenuTypeEnum } from "@/enums/MenuTypeEnum";

import SvgIcon from "@/components/SvgIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";

const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
});

const queryParams = reactive<MenuQuery>({});
const menuList = ref<MenuVO[]>([]);

const menuOptions = ref<OptionType[]>([]);

const menuProps = {
  label: 'name',
  children: 'children',
  value: 'id',
}

const formData = reactive<MenuForm>({
  pid: 0,
  status: 1,
  is_show: 1,
  sort: 50,
  type: MenuTypeEnum.CATALOG,
  method: ''
});

const rules = reactive({
  pid: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],

});

// 选择表格的行菜单ID
const selectedRowMenuId = ref<number | undefined>();

const menuCacheData = reactive({
  type: "",
  path: "",
});

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  api.listMenus(queryParams)
    .then(({ data }) => {
      menuList.value = data;
    })
    .then(() => {
      loading.value = false;
    });
}

/**
 * 查询重置
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**
 * 行点击事件
 */
function onRowClick(row: MenuVO) {
  selectedRowMenuId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function openDialog(parentId?: number, menuId?: number) {
  listMenuOptions()
    .then(({ data }) => {
      menuOptions.value = [{ id: 0, name: "顶级菜单", children: data }];
    })
    .then(() => {
      dialog.visible = true;
      if (menuId) {
        dialog.title = "编辑菜单";
        getMenuForm(menuId).then(({ data }) => {
          Object.assign(formData, data);
          menuCacheData.type = data.type;
          menuCacheData.path = data.path ?? "";
        });
      } else {
        dialog.title = "新增菜单";
        formData.pid = parentId;
      }
    });
}

/**
 * 菜单类型 change
 */
function onMenuTypeChange() {
  // 如果菜单类型改变，清空路由路径；未改变在切换后还原路由路径
  if (formData.type !== menuCacheData.type) {
    formData.path = "";
  } else {
    formData.path = menuCacheData.path;
  }
  if(formData.method == ""){
    formData.method = "get"
  }
}

/**
 * 菜单保存提交
 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.id;
      if (menuId) {
        updateMenu(menuId, formData).then(() => {
          ElMessage.success("修改成功");
          closeDialog();
          handleQuery();
        });
      } else {
        addMenu(formData).then(() => {
          ElMessage.success("新增成功");
          closeDialog();
          handleQuery();
        });
      }
    }
  });
}

/**
 * 删除菜单
 * @param menuId 菜单ID
 */
function handleDelete(menuId: number) {
  if (!menuId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteMenu(menuId).then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      });
    })
    .catch(() => ElMessage.info("已取消删除"));
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.id = undefined;
  formData.pid = 0;
  formData.status = 1;
  formData.is_show = 1;
  formData.sort = 50;
  formData.method = "get";
  formData.route = undefined;
  formData.menu_path = undefined;
  formData.path = undefined;

}

function onStatusChange(row){
	setStatusMenu(row.id,row.status).then(() => {

	});
}

function onShowChange(row){
	setShowMenu(row.id,row.is_show).then(() => {

	});
}

onMounted(() => {
  handleQuery();
});
</script>
